package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.CustomerInfoMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.WaClientMapper;
import com.ruoyi.system.service.ICustomerInfoService;
import com.ruoyi.system.service.IWaUserService_copy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户 业务层处理
 */
@Service
public class WaUserServiceImpl_copy implements IWaUserService_copy {
    private static final Logger log = LoggerFactory.getLogger(WaUserServiceImpl_copy.class);

    @Autowired
    private CustomerInfoMapper waUserMapper;

    @Autowired
    private WaClientMapper waClientMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisCache redisCache;

    @Value("${devicesPath.syncURL}")
    private String devicesSyncURL;

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<CustomerInfo> selectUserList(CustomerInfo cusUser) {
        List<CustomerInfo> list = waUserMapper.selectUserList(cusUser);
//        CustomerChat customerChat1 = new CustomerChat();
//        customerChat1.setCustomerNumber(null);
//        customerChat1.setCreateTime(null);
//
//        List<CustomerChat> list111 = waClientMapper.selectClientTotal(customerChat1);
//        list111.parallelStream().forEach(user -> {
//            Object objext = redisCache.getCacheObject(user.getClientNumber() + "-send_message");
//            if (StringUtils.isNotNull(objext)) {
//                String status = String.valueOf(objext);
//                if (Integer.valueOf(status) != user.getStatus()) {
//                    user.setStatus(Integer.valueOf(status));
//                    waClientMapper.updateCustomerChat(user);
//                }
//            }
//        });

//        list.parallelStream().forEach(user -> {
//            redisCache.setCacheObject(user.getContactNumber() + "-send_message","1");
//        });
//            f'{phone}-send_message'

//            CustomerChat customerChat = new CustomerChat();
//            customerChat.setCustomerNumber(user.getContactName());
//            customerChat.setCreateTime(null);
//            List<CustomerChat> list1 = waClientMapper.selectSendTotal(customerChat);
//            List<CustomerChat> list3 = waClientMapper.selectClientTotal(customerChat);
//            customerChat.setCreateTime(new Date());
//            List<CustomerChat> list2 = waClientMapper.selectToDaySendTotal(customerChat);
//            List<CustomerChat> list4 = waClientMapper.selectToDayClientTotal(customerChat);
//
//            String sendTotal = list1.size() + "";
//            String toDaySendTotal = list2.size() + "";
//            String clientTotal = list3.size() + "";
//            String toDayClientTotal = list4.size() + "";
//
////            cusUser.getLinkStatus()
//
//            user.setSendTotal(sendTotal);
//            user.setToDaySendTotal(toDaySendTotal);
//            user.setClientTotal(clientTotal);
//            user.setToDayClientTotal(toDayClientTotal);
//
//            Object object = redisCache.getCacheObject(user.getContactName() + ":status");
//            if (!String.valueOf(object).equals(user.getLinkStatus())) {
//                user.setLinkStatus(String.valueOf(object));
//                updateUser(user);
//            }
//        });

//        for (CusUser user : list) {
//            CustomerChat customerChat = new CustomerChat();
//            customerChat.setCustomerNumber(user.getContactName());
//            customerChat.setCreateTime(null);
//            List<CustomerChat> list1 = waClientMapper.selectSendTotal(customerChat);
//            List<CustomerChat> list3 = waClientMapper.selectClientTotal(customerChat);
//            customerChat.setCreateTime(new Date());
//            List<CustomerChat> list2 = waClientMapper.selectToDaySendTotal(customerChat);
//            List<CustomerChat> list4 = waClientMapper.selectToDayClientTotal(customerChat);
//
//            String sendTotal = list1.size() + "";
//            String toDaySendTotal = list2.size() + "";
//            String clientTotal = list3.size() + "";
//            String toDayClientTotal = list4.size() + "";
//
////            cusUser.getLinkStatus()
//
//            user.setSendTotal(sendTotal);
//            user.setToDaySendTotal(toDaySendTotal);
//            user.setClientTotal(clientTotal);
//            user.setToDayClientTotal(toDayClientTotal);
//
//            Object object = redisCache.getCacheObject(user.getContactName() + ":status");
//            if (!String.valueOf(object).equals(user.getLinkStatus())) {
//                user.setLinkStatus(String.valueOf(object));
//                updateUser(user);
//            }
//
//
//        }
//        Object groupNum = redisCache.getCacheObject("job_code:customer_number");
//        String groupNumber = String.valueOf(groupNum);
//        Object groupN = redisCache.getCacheObject("job_code:groupName");
//        String groupName = String.valueOf(groupN);
//        Object telegramN = redisCache.getCacheObject("job_telegramName");
//        String telegramName = String.valueOf(telegramN);
//        for (CusUser user : list) {
////            String group_key = "ipaddress:" + user.getContactNumber();
//            try {
////                Object o = redisCache.getCacheObject(group_key);
////                if (StringUtils.isNotNull(o)) {
//                user.setTelegramName(telegramName);
//                user.setGroupName(groupName);
//                user.setGroupNumber(groupNumber);
//                updateUser(user);
////                }
//            } catch (JSONException e) {
////                log.error("反序列化错误，key: " + group_key + ", value: " + redisCache.getCacheObject(group_key), e);
//            }
//        }
        return list;
    }

    @Override
    public CustomerInfo selectUserByUserName(String customerName) {
        return waUserMapper.selectUserByUserName(customerName);
    }

    @Override
    public CustomerInfo selectChatById(String id) {
        return waUserMapper.selectChatById(id);
    }

    @Override
    public CustomerInfo selectUserByNumber(String contactNumber) {
        return waUserMapper.selectUserByNumber(contactNumber);
    }

    @Override
    public int insertUser(CustomerInfo user) {
        //根据用户名称查找用户id及部门id
//        if (StringUtils.isNotEmpty(user.getIpaddress())) {
//            String group_key = "ipaddress:" + user.getContactNumber();
//            redisCache.setCacheObject(group_key, user.getIpaddress());
//        }
        return waUserMapper.insertUser(user);
    }


    @Override
    public int updateChatStatus(CustomerInfo user) {
        if (StringUtils.isNotEmpty(user.getIpaddress())) {
            String group_key = "ipaddress:" + user.getContactNumber();
            redisCache.setCacheObject(group_key, user.getIpaddress());
        }
        return waUserMapper.updateChatStatus(user);
    }

    @Override
    public int updateLinkStatus(CustomerInfo user) {
        if (StringUtils.isNotEmpty(user.getIpaddress())) {
            String group_key = "ipaddress:" + user.getContactNumber();
            redisCache.setCacheObject(group_key, user.getIpaddress());
        }
        return waUserMapper.updateLinkStatus(user);
    }


    @Override
    public int resetUserPwd(CustomerInfo user) {
        return waUserMapper.resetUserPwd(user);
    }

    @Override
    public int deleteUserByNumber(String contactNumber) {
        return waUserMapper.deleteUserByNumber(contactNumber);
    }

    @Override
    public int deleteUserByNumbers(String[] id) {
        return waUserMapper.deleteUserByNumbers(id);
    }

    @Override
    public boolean checkContactNumberUnique(CustomerInfo user) {
        String customerId = StringUtils.isNull(user.getId()) ? "" : user.getId();
        CustomerInfo info = waUserMapper.checkContactNumberUnique(user.getContactNumber());
        if (StringUtils.isNotNull(info)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<CustomerInfo> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Object groupNum = redisCache.getCacheObject("job_code:customer_number");
        String groupNumber = String.valueOf(groupNum);
        Object groupN = redisCache.getCacheObject("job_code:groupName");
        String groupName = String.valueOf(groupN);
        Object telegramN = redisCache.getCacheObject("job_telegramName");
        String telegramName = String.valueOf(telegramN);
        for (CustomerInfo user : userList) {
            try {
                // 验证是否存在这个用户
                CustomerInfo u = waUserMapper.selectUserByNumber(user.getContactNumber());
//                if (StringUtils.isNotEmpty(u.getUserName())) {
                if (StringUtils.isNull(u)) {
                    user.setGroupName(groupName);
                    user.setGroupNumber(groupNumber);
                    user.setTelegramName(telegramName);
                    insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getContactNumber() + " 导入成功");
                } else if (isUpdateSupport) {
                    if (StringUtils.isNotEmpty(user.getIpaddress())) {
                        String group_key = "ipaddress:" + user.getContactNumber();
                        redisCache.setCacheObject(group_key, user.getIpaddress());
                    }
                    waUserMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getContactNumber() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getContactNumber() + " 已存在");
                }

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getContactNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String getLinkStatus(String contactNumbers) {
        return null;
    }

    @Override
    public int selectToids(BulkSendName bulkSendName) {
        List<CustomerInfo> list = waUserMapper.selectToids(bulkSendName.getId());
        for (CustomerInfo user : list) {
            String group_key = "job_code:" + user.getContactNumber() + ":groupName";
            redisCache.setCacheObject(group_key, bulkSendName.getBulkName());
            String group_number = "job_code:" + user.getContactNumber() + ":customer_number";
            if (StringUtils.isNotEmpty(bulkSendName.getCusNumber())) {
                redisCache.setCacheObject(group_number, bulkSendName.getCusNumber());
            } else {
                redisCache.setCacheObject(group_number, user.getContactNumber());
            }
            user.setGroupNumber(bulkSendName.getCusNumber());
            user.setGroupName(bulkSendName.getBulkName());
            waUserMapper.updateUser(user);
        }


        return 1;
    }

    @Override
    public int selectToApi(BulkSendName bulkSendName) {
        List<CustomerInfo> list = waUserMapper.selectToids(bulkSendName.getId());
        for (CustomerInfo user : list) {
//            String group_key = "ipaddress:" + user.getContactNumber();
//            redisCache.setCacheObject(group_key, bulkSendName.getApiUrl());
            user.setIpaddress(bulkSendName.getApiUrl());
            updateUser(user);
        }
        return 1;
    }

    @Override
    public int updateUser(CustomerInfo user) {
        if (StringUtils.isNotEmpty(user.getIpaddress())) {
            String group_key = "ipaddress:" + user.getContactNumber();
            redisCache.setCacheObject(group_key, user.getIpaddress());
        }
        int sd = waUserMapper.updateUser(user);
//        `salesman_info:${customerNumber}`;
        redisCache.deleteObject("salesman_info:" + user.getContactNumber());
        return sd;
    }

    @Override
    public int relpyback(BulkSendName bulkSendName) {
        return 0;
    }


    @Override
    public List<CustomerInfo> selectUserByName(String userName) {
        List<CustomerInfo> list = waUserMapper.selectUserByName(userName);
        return list;
    }

    @Override
    public String reconnect() {
//        CusUser user = new CusUser();
//        user.setLinkStatus("1");
//        List<CusUser> list = waUserMapper.selectUserList(user);
//
//        String ids = list.stream()
//                .map(CusUser::getId) // 假设getId()是获取用户ID的方法
//                .map(String::valueOf) // 转换为字符串
//                .collect(Collectors.joining(",")); // 以,连接
//
//        String rspStr = HttpUtils.sendGet(newChatURL + ids);
//        AjaxResult ajax = AjaxResult.success();
//        ajax.put("data", rspStr);

        return null;
    }

    @Override
    public int setTelegram(BulkSendName bulkSendName) {
        List<CustomerInfo> list = waUserMapper.selectToids(bulkSendName.getId());
        for (CustomerInfo user : list) {
            String teleKey = "job_code:" + user.getContactNumber() + ":telegramName";
//            redisCache.setCacheObject(teleKey, bulkSendName.getTelegramName());
//            String group_number = "job_code:" + user.getContactNumber() + ":telegramName";
            if (StringUtils.isNotEmpty(bulkSendName.getTelegramName())) {
                redisCache.setCacheObject(teleKey, bulkSendName.getTelegramName());
                user.setTelegramName(bulkSendName.getTelegramName());
                waUserMapper.updateUser(user);
            }

        }
        return 1;
    }

    @Override
    public int syncDevices(SysUser user) {
        try {
            String rspStr = HttpUtils.sendGet(devicesSyncURL);
            List<DevicesData> devicesList = JSON.parseObject(rspStr, new TypeReference<List<DevicesData>>() {
            });
            redisCache.deleteObject("devices_list");
            redisCache.setCacheList("devices_list", devicesList);
//            redisCache.getCacheList("devices_list");
            for (DevicesData device : devicesList) {
                CustomerInfo cusUser = new CustomerInfo();
                cusUser.setUserId(user.getUserId());
                cusUser.setDeptId(user.getDeptId());
                cusUser.setContactName(device.getDeviceName());
                cusUser.setLinkStatus(device.getDeviceState() + "");
                cusUser.setIpaddress(device.getIp());
                cusUser.setContactNumber(device.getDeviceId());
                CustomerInfo u = waUserMapper.selectUserByDevicesId(cusUser);
                if (StringUtils.isNull(u)) {

                    redisCache.setCacheObject(cusUser.getContactName() + ":status", cusUser.getLinkStatus());
                    insertUser(cusUser);
                } else {
                    cusUser.setId(u.getId());
//                    Object object = redisCache.getCacheObject(cusUser.getContactName() + ":status");
//                    String links = String.valueOf(object);
//                    if (!links.equals("3")) {
//                        redisCache.setCacheObject(cusUser.getContactName() + ":status", cusUser.getLinkStatus());
//                    }
                    redisCache.setCacheObject(cusUser.getContactName() + ":status", cusUser.getLinkStatus());
                    updateUser(cusUser);
                    CustomerChat chat = new CustomerChat();
                    chat.setCustomerNumber(u.getContactName());
                    chat.setCustomerName(cusUser.getContactName());
                    waClientMapper.updateCustomerChatBycustomerNumber(chat);
                }
            }
        } catch (Exception e) {
            log.error("" + e);
            return 0;
        }
        return 1;
    }

    @Override
    public int selectById(String[] ids) {
        List<CustomerInfo> list = waUserMapper.selectToids(ids);
        for (CustomerInfo user : list) {
            redisCache.setCacheObject(user.getContactName() + ":isStop", "1");
            redisCache.setCacheObject(user.getContactName() + ":status", "4");
//            redis_util.set_key(f'{contact_name}:status', '4')
        }
        return 1;
    }

}
